<template>
  <div>
    <div class="list-card-operation">
      <div class="search-input">
        <t-input v-model="searchValue" :placeholder="t('pages.listCard.placeholder')" clearable>
          <template #suffix-icon>
            <search-icon v-if="searchValue === ''" size="var(--td-comp-size-xxxs)" />
          </template>
        </t-input>
      </div>
    </div>

    <template v-if="serverList.length > 0 && !dataLoading">
      <div class="list-card-items">
        <t-row :gutter="[16, 16]">
          <t-col v-for="(server, index) in serverList" :key="index" :lg="4" :xs="6" :xl="3">
            <server-card
              class="list-card-item"
              :server="server"
              @restart-server="handleRestartServer"
              @stop-server="handleStopServer"
            />
          </t-col>
        </t-row>
      </div>
    </template>

    <div v-else-if="dataLoading" class="list-card-loading">
      <t-loading size="large" text="加载数据中..." />
    </div>
  </div>
</template>

<script lang="ts">
export default {
  name: 'ListCard',
};
</script>

<script setup lang="ts">
import { SearchIcon } from 'tdesign-icons-vue-next';
import { MessagePlugin } from 'tdesign-vue-next';
import { onMounted, ref } from 'vue';

import type { ServerInfo } from '@/api/model/serverModel';
import { getServers, restartServer, stopServer } from '@/api/server';
import ServerCard from '@/components/server-card/index.vue';
import { t } from '@/locales';

const dataLoading = ref(true);
const serverList = ref<Array<ServerInfo>>([]);

onMounted(() => {
  handleCardList();
});

const handleCardList = async () => {
  dataLoading.value = true;
  serverList.value = await getServers();
  dataLoading.value = false;
};

const searchValue = ref('');

const handleRestartServer = async (server: ServerInfo) => {
  await restartServer(server.name);
  serverList.value = await getServers();
  MessagePlugin.success('重启成功');
};

const handleStopServer = async (server: ServerInfo) => {
  await stopServer(server.name);
  serverList.value = await getServers();
  MessagePlugin.success('停止成功');
};
</script>

<style lang="less" scoped>
.list-card {
  height: 100%;

  &-operation {
    display: flex;
    justify-content: space-between;
    margin-bottom: var(--td-comp-margin-xxl);

    .search-input {
      width: 360px;
    }
  }

  &-item {
    padding: var(--td-comp-paddingTB-xl) var(--td-comp-paddingTB-xl);

    :deep(.t-card__header) {
      padding: 0;
    }

    :deep(.t-card__body) {
      padding: 0;
      margin-top: var(--td-comp-margin-xxl);
      margin-bottom: var(--td-comp-margin-xxl);
    }

    :deep(.t-card__footer) {
      padding: 0;
    }
  }

  &-pagination {
    padding: var(--td-comp-paddingTB-xl) var(--td-comp-paddingTB-xl);
  }

  &-loading {
    height: 100%;
    width: 100%;
    display: flex;
    align-items: center;
    justify-content: center;
  }
}
</style>
